package com.care.controller.weixin;

import com.alibaba.fastjson.JSONObject;
import com.care.author.AuthRequired;
import com.care.controller.vo.JsonResult;
import com.care.dao.mapper.AdminMapper;
import com.care.dao.mapper.ForumCommentMapper;
import com.care.dao.mapper.ForumMapper;
import com.care.dao.mapper.UserMapper;
import com.care.dao.model.Forum;
import com.care.dao.model.ForumComment;
import com.care.dao.model.User;
import com.care.utils.HtmlFilterUtil;
import com.care.utils.page.PageView;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 前台：论坛API
 * @author xujinnan
 *
 */
@RequestMapping("/api/forum")
@RestController
public class ForumApiController extends ApiBaseController {

    @Autowired
    private ForumMapper forumMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private ForumCommentMapper forumCommentMapper;

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //注册自定义的编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 帖子列表
     * @param reqMap
     * @param request
     * @return
     */
    @RequestMapping("list")
    public JsonResult blogList(@RequestBody Map<String, Object> reqMap, HttpServletRequest request) {
        PageView<Forum> pageView = new PageView<>();
        pageView = pageView.startPage(reqMap);
        JsonResult result = new JsonResult(true, "0", "查询成功");
        Example example = new Example(Forum.class);
        Criteria criteria = example.createCriteria();
        if(reqMap.containsKey("kw")&&StringUtils.isNotBlank(reqMap.get("kw").toString())){
            //查询帖子
            criteria.andLike("title", "%"+reqMap.get("kw").toString()+"%");
        }
        example.orderBy("publishTime").desc();
        List<Forum> list = forumMapper.selectByExampleAndRowBounds(example, new RowBounds(pageView.getFirstResult(), pageView.getMaxresult()));
        for(Forum forum:list){
            forum.setUser(userMapper.selectByPrimaryKey(forum.getUserId()));
            forum.setAdmin(adminMapper.selectByPrimaryKey(forum.getAdminId()));
            forum.setContent(HtmlFilterUtil.Html2Text(forum.getContent()));
            if(StringUtils.isNotBlank(forum.getPics())) {
                String[] url = forum.getPics().split(",");
                List<String> urls = new ArrayList<>();
                for (int i=0; i<url.length; i++) {
                    urls.add(url[i]);
                }
                forum.setPicList(urls);
            }
        }
        pageView.setRecords(list);
        pageView.setTotalrecord(forumMapper.selectCountByExample(example));
        result.setData(pageView);
        return result;
    }

    /**
     * 帖子详情
     * @param forumId
     * @return
     */
    @RequestMapping("detail")
    public JsonResult forumDetail(Integer forumId) {
        JsonResult result = new JsonResult(true, "0", "查询成功");
        Forum forum = forumMapper.selectByPrimaryKey(forumId);
        forum.setUser(userMapper.selectByPrimaryKey(forum.getUserId()));
        forum.setAdmin(adminMapper.selectByPrimaryKey(forum.getAdminId()));
        JSONObject jo = new JSONObject();
        jo.put("forum", forum);
        result.setData(jo);
        Example example = new Example(ForumComment.class);
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("forumId",forumId);
        example.orderBy("publishTime").desc();
        List<ForumComment> forumCommentList = forumCommentMapper.selectByExample(example);
        for(ForumComment fc:forumCommentList){
            fc.setUser(userMapper.selectByPrimaryKey(fc.getUserId()));
            fc.setAdmin(adminMapper.selectByPrimaryKey(fc.getAdminId()));
        }
        if(StringUtils.isNotBlank(forum.getPics())) {
            String[] url = forum.getPics().split(",");
            List<String> urls = new ArrayList<>();
            for (int i=0; i<url.length; i++) {
                urls.add(url[i]);
            }
            forum.setPicList(urls);
        }
        jo.put("comments", forumCommentList);
        return result;
    }

    /**
     * 发帖
     * @param request
     * @param req
     * @return
     */
    @PostMapping("save")
    @AuthRequired
    public JsonResult saveBlog(@RequestBody JSONObject req, HttpServletRequest request) {
        JsonResult result = new JsonResult(true, "0", "保存成功");
        Forum forum = JSONObject.parseObject(req.toJSONString(), Forum.class);
        User user = (User) request.getAttribute("loginUser");
        try {
            forum.setPublishTime(new Date());
            forum.setUserId(user.getUserId());
            forumMapper.insertSelective(forum);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("保存失败");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 发表评论
     * @param request
     * @param req
     * @return
     */
    @RequestMapping("comment/save")
    public JsonResult saveForumComment(HttpServletRequest request, @RequestBody JSONObject req) {
        JsonResult result = new JsonResult(true, "0", "保存成功");
        User user = (User) request.getAttribute("loginUser");
        ForumComment comment = JSONObject.parseObject(req.toJSONString(), ForumComment.class);
        try {
            comment.setPublishTime(new Date());
            comment.setUserId(user.getUserId());
            forumCommentMapper.insertSelective(comment);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("保存失败");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 查询小程序用户发的帖子
     * @param reqMap
     * @param request
     * @return
     */
    @RequestMapping("my/list")
    @AuthRequired
    public JsonResult myForumList(@RequestBody Map<String, Object> reqMap, HttpServletRequest request) {
        PageView<Forum> pageView = new PageView<>();
        User user = (User) request.getAttribute("loginUser");
        pageView = pageView.startPage(reqMap);
        JsonResult result = new JsonResult(true, "0", "查询成功");
        Example example = new Example(Forum.class);
        Criteria criteria = example.createCriteria();
        if(reqMap.containsKey("kw")&&StringUtils.isNotBlank(reqMap.get("kw").toString())){
            //查询帖子
            criteria.andLike("title", "%"+reqMap.get("kw").toString()+"%");
        }
        criteria.andEqualTo("userId", user.getUserId());
        example.orderBy("publishTime").desc();
        List<Forum> list = forumMapper.selectByExampleAndRowBounds(example, new RowBounds(pageView.getFirstResult(), pageView.getMaxresult()));
        for(Forum forum:list){
            forum.setUser(userMapper.selectByPrimaryKey(forum.getUserId()));
            forum.setAdmin(adminMapper.selectByPrimaryKey(forum.getAdminId()));
        }
        pageView.setRecords(list);
        pageView.setTotalrecord(forumMapper.selectCountByExample(example));
        result.setData(pageView);
        return result;
    }
}
